#!/usr/bin/env python
# encoding: utf-8
'''
@author: zhaowenpeng
@contact: winston@peipeiyun.com
@software: garner
@file: __init__.py.py
@time: 2020/7/17 3:43 下午
@desc:
'''

import time
from . import DBUtil
from peewee import Model, ModelUpdate,ModelInsert,TimestampField,CharField
from core.db import database

class BaseModel(Model,DBUtil):

    show_id = CharField(max_length=32, verbose_name='展示ID', help_text="展示ID",default='')
    add_time = TimestampField(verbose_name='添加时间',help_text='添加时间',index=True,default=0)
    upd_time = TimestampField(verbose_name='更新时间',help_text='更新时间',default=0)
    delete_time = TimestampField(verbose_name='删除', help_text='删除', default=0,index=True)

    class Meta:
        database=database

    @classmethod
    def insert(cls, __data=None, **insert):
        insert.update({
                'add_time':time.time(),
                'upd_time':time.time()
        })
        return ModelInsert(cls, cls._normalize_data(__data, insert))
    @classmethod
    def update(cls, __data=None, **update):
        update.update({'upd_time':time.time()})
        return ModelUpdate(cls, cls._normalize_data(__data, update))
    @classmethod
    def insert_many(cls, rows, fields=None):
        for row in rows:
            row.update({
                    'add_time': time.time(),
                    'upd_time': time.time()
            })
        return ModelInsert(cls, insert=rows, columns=fields)

    def _dict_(self,keys):
        data = {key: getattr(self, key) for key in keys}
        data.pop('id')
        return data

    def to_title(self,keys=None):
        if not keys:
            keys = self._meta.columns.keys()
            pop_keys = ['id','add_time','upd_time']
            keys = list(set(keys).difference(set(pop_keys)))
        titles = {key: getattr(self._meta.fields.get(key), 'verbose_name') for key in keys}
        return titles

    @classmethod
    def get_title(cls,keys=None):
        if not keys:
            keys = cls._meta.columns.keys()
            pop_keys = ['id','add_time','upd_time']
            keys = list(set(keys).difference(set(pop_keys)))
        titles = {key: getattr(cls._meta.fields.get(key), 'verbose_name') for key in keys}
        return titles

